﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace HDS.Common.Helper
{
    public static class EnumsHelper
    {
        /// <summary>
        /// 列举所有枚举值和描述
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Dictionary<int, string> GetDescriptionDictionary<T>(bool orderByDescending = false) where T : struct
        {
            Type type = typeof(T);
            Dictionary<int, string> dictionary = new Dictionary<int, string>();
            foreach (int item in System.Enum.GetValues(type))
            {
                string description = string.Empty;
                FieldInfo fieldInfo = type.GetField(System.Enum.GetName(type, item));
                if (fieldInfo == null)
                {
                    continue;
                }
                DescriptionAttribute da = (DescriptionAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));
                if (da == null)
                {
                    continue;
                }
                description = da.Description;

                dictionary.Add(item, description);
            }
            if(orderByDescending)
                return dictionary.OrderByDescending(e => e.Key).ToDictionary(e => e.Key, e => e.Value);
            else
                return dictionary.OrderBy(e => e.Key).ToDictionary(e => e.Key, e => e.Value);
        }

        /// <summary>
        /// 获取指定枚举值的描述
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetDescription<T>(T request) where T : struct
        {
            try
            {
                Type type = request.GetType();
                FieldInfo fieldInfo = type.GetField(request.ToString());

                if (fieldInfo == null) { return string.Empty; }

                DescriptionAttribute da = (DescriptionAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));

                if (da != null)
                {
                    return da.Description;
                }
                else
                {
                    return string.Empty;
                }
            }
            catch
            {
                return string.Empty;
            }
        }
    }
}
